OCaml Variants and Algebraic Data Types
Table of Contents
1. Variants
A variant is a data type representing a value that is one of several possibilities. At their simplest, variants are like enums.
type day = Sun | Mon | Tue | Wed | Thu | Fri | Sat
let d = Tue
The individual names of the values of a variants are called constructors in OCaml. We can perform pattern matching on variants.
let int_of_day d =
match d with
| Sun -> 1
| Mon -> 2
| Tue -> 3
| Wed -> 4
| Thu -> 5
| Fri -> 6
| Sat -> 7
1.1. Scope of Constructors
Suppose there are 2 types defined, with overlapped constructor names.
type T1 = C | D
type T2 = D | E
let x = D
Then, the type defined later wins, which means that, variable x is of type T2.